package cn.droidlover.xdroidmvp.net.gson;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.IOException;
import java.lang.reflect.Type;

import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.BaseModel;
import okhttp3.ResponseBody;
import retrofit2.Converter;

public class GsonResponseBodyConverter_1<T> implements Converter<ResponseBody,T> {

    private final Gson gson;
    private final Type type;
    public GsonResponseBodyConverter_1(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        /*
            解决同字段不同类型的json数据
            状态码code值  如果为ApiException.codes中的 视为成功 就会返回type类型的数据
            状态码code值  如果不为200 视为失败 将code抛出 后续根据code值进行异常处理
         */
            String response = value.string();
            try {
                BaseModel baseModel = gson.fromJson(response,BaseModel.class);
//                if (200==baseModel.code){
                if(checkCode(baseModel.code)){
                    return gson.fromJson(response, type);
                }else {
                        throw new ApiException(baseModel.code,baseModel.msg);
                }
            }finally {
                value.close();
            }
    }

    public boolean checkCode(int code){
        for (int i:ApiException.codes){
            if (i==code)return true;
        }
        return false;
    }
}
